package com.net.xpay.admin.controller.admin;


import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.PhoneUtil;
import com.net.xpay.admin.vo.UserRegisterVo;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.partner.PartnerUserFilings;
import com.net.xpay.common.enums.config.CommonSysConfigKey;
import com.net.xpay.common.enums.partner.PartnerUserFilingsAuditStatus;
import com.net.xpay.common.enums.user.ClientFrom;
import com.net.xpay.common.enums.user.UserTag;
import com.net.xpay.common.helper.CommonSysConfigHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.partner.PartnerUserFilingsManager;
import com.net.xpay.common.model.PartnerUserFilingsSubmitModel;
import com.net.xpay.common.model.RegisterModel;
import com.net.xpay.common.model.search.PartnerUserFilingsSearchModel;
import com.net.xpay.common.service.PartnerUserFilingsService;
import com.net.xpay.common.service.UserService;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.model.AdminPartnerUserFilingsAuditModel;
import com.net.xpay.core.model.IdModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 2019/4/1 14:45
 */
@Slf4j
@RestController
@RequestMapping("/admin/partner-user-filings")
@Api(tags = "运营/开户申请", description = "运营 开户申请 net")
public class AdminPartnerUserFilingsController {

    @Autowired
    private PartnerUserFilingsManager partnerUserFilingsManager;

    @Autowired
    private PartnerUserFilingsService partnerUserFilingsService;

    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CommonSysConfigHelper commonSysConfigHelper;
    @Autowired
    private UserManager userManager;


    @ApiOperation("开户申请分页搜索")
    @PostMapping("/search")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'partner-user-filings::search')")
    public ResultPagedList<PartnerUserFilings> search(@RequestBody PartnerUserFilingsSearchModel searchModel) {
        if (searchModel.getAuditStatus() == null) {
            searchModel.setAuditStatus(PartnerUserFilingsAuditStatus.NORMAL);
        }
        List<PartnerUserFilings> records = partnerUserFilingsManager.search(searchModel);
        long count = partnerUserFilingsManager.searchCount(searchModel);

        return new ResultPagedList<>(records, count, searchModel);
    }

    @ApiOperation("开户申请注册")
    @PostMapping("/register")
    @ResponseBody
    public ResultData<Boolean> search(@RequestBody PartnerUserFilingsSubmitModel model) {
        Partner partner = new Partner();
        partner.setMobile(model.getMobile());
        partner.setName(model.getBusinessName());
        partnerUserFilingsService.submitPartnerUserFilings(partner, model);
        return new ResultData<>(true);
    }

    @ApiOperation("审核通过")
    @PostMapping("/audit-success")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'partner-user-filings::audit-success')")
    public ResultData<UserRegisterVo> auditSuccess(@RequestBody IdModel idModel) {
        Preconditions.checkArgument(idModel.getId() != null);

        PartnerUserFilings record = partnerUserFilingsManager.getById(idModel.getId());

        if (record == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "未找到记录");
        }
        if (record.getAuditStatus() != PartnerUserFilingsAuditStatus.AUDITING) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "当前状态不是待审核");
        }
        // 确认手机号未被注册
        if (userManager.findByMobile(record.getMobile()) != null) {
            throw new BusinessException(PoseidonErrorCode.MOBILE_DUPLICATED, "手机号已经被注册");
        }

        RegisterModel registerModel = new RegisterModel();
        registerModel.setMobile(record.getMobile());
        registerModel.setName(record.getBusinessName());
        String randomPassword = Strings.padStart("" + RandomUtils.nextInt(0, 1000000), 6, '0');
        registerModel.setPassword(randomPassword);
        registerModel.setClientFrom(ClientFrom.PC_WEB);
        registerModel.setAdminRegister(true);
        registerModel.setUserTag(UserTag.PLATFORM);
        User user = userService.registerInternal(registerModel);
        // 审批通过
        partnerUserFilingsService.auditSuccess(record);

        String website = commonSysConfigHelper.getString(CommonSysConfigKey.MERCHANT_DOMAIN);
        String openDomain = commonSysConfigHelper.getString(CommonSysConfigKey.OPEN_DOMAIN);
        String openapiDomain = commonSysConfigHelper.getString(CommonSysConfigKey.OPENAPI_DOMAIN);
        UserRegisterVo vo = new UserRegisterVo();
        vo.setMobile(user.getMobile());
        vo.setName(user.getName());
        vo.setPassword(randomPassword);
        vo.setWebsite(website);
        vo.setOpenDomain(openDomain);
        vo.setOpenapiDomain(openapiDomain);
        return new ResultData<>(vo);
    }

    @ApiOperation("审核失败")
    @PostMapping("/audit-fail")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ADMIN', 'partner-user-filings::audit-fail')")
    public ResultData<Boolean> auditFail(@RequestBody AdminPartnerUserFilingsAuditModel model) {
        partnerUserFilingsService.auditFail(model);
        return new ResultData<>(true);
    }

}
